// -*- coding: utf-8 -*- 
/**
 * Project: AlgorithmsLearn
 *
 * @author: yanking
 * Create time: 2022-03-20 15:10
 * IDE: IntelliJ IDEA
 * Introduction:
 */
package com.LeetCodeT.ArraysTrain;

import java.util.Arrays;

public class ThreeSumClosestUpdate {
    /**
     * 使用双指针
     * 通过min 和 max 减小比较时间  -> 因为是获取最近的结果和，所以数据的总和需要和target的值相减少
     * 任意选取的整数数字可以相同
     *
     * @param nums
     * @param target
     * @return
     */
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int n = nums.length, cur = 0, diff = Integer.MAX_VALUE, curDiff = 0, res = 0;
        for (int p = 0; p < n - 2; p++) {
            // 以p开头组合的最小值
            int h = p + 1, t = n - 1;
            while (h < t) {
                cur = nums[p] + nums[h] + nums[t];
                curDiff = Math.abs(cur - target);
                if (curDiff < diff) {
                    res = cur;
                    diff = curDiff;
                } else if (cur < target) {
                    // 当前组合值小
                    h++;
                } else {
                    // 当前组合值大
                    t--;
                }
            }
        }
        return res;
    }
}